import json
import os
import sys
import zipfile

from nameko.rpc import rpc

sys.path.append("../")

from utils import dbutil,Utils
from config import Config

class Dataset:
    name = "data_management"  # 自定义服务名称

    @rpc  # 入口点标记
    def upload_dataset(self, user_id, file):
        """
        上传数据集
        :param user_id: 用户id
        :param file_name: 数据集名称
        :param dataset_file_path: 数据集存储路径
        :return:
        """
        try:
            dataset_path=os.path.join(Config.dataset_file_path.replace('user_id', user_id),file)
            sql = r"""
                insert into app_dataset (
                user_id,dataset_name,dataset_path,create_time
                )
                value (
                '{}','{}',{},now()
                )
            """.format(user_id,file,repr(dataset_path))
            dbutil.insert(sql)
            return 200
        except:
            return 500

    @rpc
    def del_dataset(self, user_id,dataset_name):
        try:
            sql = """
                    select dataset_path from app_dataset
                    where user_id='{}' and dataset_name = '{}'
                """.format(user_id, dataset_name)

            result = dbutil.query(sql)
            if result:
                dataset_path = result[0][0]
                # 删除存放对应数据集的文件夹
                dataset_path = os.path.join(dataset_path, '')
                Utils.del_dir(dataset_path)
                # 若下载数据集时产生的压缩包存在，则删除
                dataset_zip_path = dataset_path[:-1] + '.zip'
                if os.path.exists(dataset_zip_path):
                    os.remove(dataset_zip_path)
                # 删除数据库记录
                sql = """
                        delete from app_dataset where user_id='{}' and dataset_name = '{}'
                    """.format(user_id, dataset_name)
                dbutil.delete(sql)
                messages = "success"
                status = 200
            else:
                messages = "数据集{}不存在".format(dataset_name)
                status = 404
        except:
            status = 500
            messages = "failed"

        result = {
            'msg': messages,
            'status': status
        }
        return json.dumps(result)

    @rpc
    def get_dataset(self,user_id,dataset_name):
        """
        获取数据集信息
        :param dataset_name:
        :return:
        """
        try:
            sql="""
                select * from app_dataset
                where user_id='{}' and dataset_name = '{}'
            """.format(user_id,dataset_name)

            datas = dbutil.query(sql)
            # ((9, '1810716631', 'bert_data', datetime.datetime(2022, 5, 14, 17, 55, 31), 'E:\\毕业设计。。。\\bert_data'),)
            if datas:
                data = datas[0]
                result = {
                    "msg": "success",
                    'status': 200,
                    'data':{
                        'user_id':data[1],
                        'dataset_name':data[2],
                        # 序列化datetime
                        'create_time':data[3].strftime("%Y-%m-%d %H:%M:%S"),
                    }
                }
            else:
                result = {
                    "msg": "数据集{}不存在".format(dataset_name),
                    'status': 404
                }
        except:
            result = {
                'msg': "程序执行出错",
                'status': 500
            }
        return json.dumps(result)

    @rpc
    def get_dataset_list(self,user_id):
        """
        获取数据集信息列表
        :return:
        """
        try:
            sql = """
                    select * from app_dataset where user_id = '{}'
                """.format(user_id)
            datas = dbutil.query(sql)
            if datas:
                result_list = []
                for i,item in enumerate(datas):
                    temp_dir = {}
                    temp_dir["uesr_id"] = item[1]
                    temp_dir["dataset_name"] = item[2]
                    temp_dir["create_time"] = item[3].strftime("%Y-%m-%d %H:%M:%S")
                    result_list.append(temp_dir)

                result = {
                    'msg':'success',
                    'status': 200,
                    'data': result_list
                }
            else:
                result = {
                    'msg': "用户不存在或此用户无数据集",
                    'status': 404
                }
        except:
            result = {
                'msg': "程序执行出错",
                'status': 500
            }

        return json.dumps(result)


